var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var _limitMenu = system.MENULIMIT.VIP11;
var _menuParam = config.OPTIONLIMIT;
var isRefresh = false;
var queryurl = config.BASEPATH+'vip/report/vipquota_analysis_list';

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/to_list_sub_dialog',
			data : {multiselect:false},
			width : 450,
			height : 370,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#vm_shop_code").val(selected.sp_code);
					$("#sp_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	}
}

var handle = {
	operFmatter:function(val, opt, row) {
		var html_con = "<div class='operating' data-id='" + row.id + "'>";
		if(row.id != ""){
			html_con += "<i class='iconfont i-hand' title='回访' onclick=\"handle.consumeVisit('"+row.id+"','"+row.vm_cardcode+"')\" >&#xe69b;</i>";
		}else{
			html_con += "<span class='ui-icon' style='background:none;'></span><span class='ui-icon' style='background:none;'></span>";
		}
		html_con += "</div>";
		return html_con;
	},
	changeBeginDate:function(){
		//根据输入时间，改变隐藏开始时间 begindate
		var enddate = $('#enddate').val();
		var vs_loss_day = $('#vs_loss_day').val();
		if(vs_loss_day==""){
			return;
		}
		if(isNaN(vs_loss_day) || vs_loss_day < 0){
			$('#vs_loss_day').val("0");
			vs_loss_day = "0";
		}
		var s1,s2;
		s2 = new Date(enddate.replace(/-/g, "/"));
		var days = s2.getTime()-(parseInt(vs_loss_day)*24*60*60*1000);
		s1 = new Date(days);
		var year = s1.getFullYear();
		var month = s1.getMonth()+1;
		if(month < 10){
			month = "0"+month;
		}
		var day = s1.getDate();
		if(day<10){
			day = "0"+day;
		}
		$('#begindate').val(year+"-"+month+"-"+day)
	},
	consumeVisit:function(vm_id, vm_cardcode){//消费回访
		/*if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
			return ;
		}*/
		$.dialog({ 
		   	title:'会员回访',
		   	//data:{vi_type:3},//1:会员回访 2:生日回访 3:消费回访
		   	max: false,
		   	min: false,
		   	width:900,height:450,
		   	fixed:false,
		   	drag: true,
		   	resize:false,
		   	content:'url:'+config.BASEPATH+'vip/member/vip_visit_analysis?vm_id='+vm_id+'&vi_type=1&vm_cardcode='+vm_cardcode,
		   	lock:true,
		   	close: function(){
		   		if(isRefresh){
		   			THISPAGE.reloadData();
		   			isRefresh = false;
		   		}
		   	}
		});
	}
};

var THISPAGE = {
		init:function (){
			this.initDom();
			this.loadChartLosePie();
			this.initGrid("&query_type=loss");
			this.initEvent();	
		},
		initDom:function(){
			
		},
		loadChartLosePie:function(){
			$.ajax({
				type:"POST",
				async:false,
				url:config.BASEPATH+"vip/report/member_lose_data?"+THISPAGE.buildParams(), 
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						var viphold_count = parseInt(data.data.viphold_count, 10);//会员保留数
						var loss_vip = parseInt(data.data.loss_vip, 10);//流失数
						var new_vip = parseInt(data.data.new_vip, 10);//新增会员数
						//var goUpVip = parseInt(data.data.goUpVip, 10);//升级会员数
						var total_vip = parseInt(data.data.total_vip, 10);//会员总数
						var buy_count_vip = parseInt(data.data.buy_count_vip, 10);//周期内购买人数
						var cyclevip_buy_count=parseInt(data.data.cyclevip_buy_count, 10);//周期内，新增会员的购买人数
						var buy_back_vip = total_vip-new_vip-loss_vip;
						if(total_vip == 0){
							document.getElementById("loss_vip_rate").innerHTML = "0.00%";
							document.getElementById("loss_vip_count").innerHTML = 0;
							document.getElementById("total_vip1").innerHTML = 0;
							document.getElementById("hold_vip_rate").innerHTML = "0.00%";
							document.getElementById("viphold_count").innerHTML = 0;
							document.getElementById("total_vip2").innerHTML = 0;
							document.getElementById("new_vip_rate").innerHTML = "0.00%";
							document.getElementById("new_vip_vount").innerHTML = 0;
							document.getElementById("total_vip3").innerHTML = 0;
							document.getElementById("goup_vip_rate").innerHTML = "0.00%";
							document.getElementById("goup_vip_count").innerHTML = 0;
							document.getElementById("total_vip4").innerHTML = 0;
							document.getElementById("buyback_vip_rate").innerHTML = "0.00%";
							document.getElementById("buyback_vip_count").innerHTML = 0;
							document.getElementById("total_vip5").innerHTML = 0;
							return;
						}
						var vip_counts = total_vip-new_vip;
						var loss_vip_rate = (vip_counts>0? (loss_vip/total_vip)*100 :0).toFixed(2);
						var hold_vip_rate   = (vip_counts>0? ((viphold_count)/total_vip)*100 : 0).toFixed(2);
						var new_vip_rate    = (vip_counts>0? (new_vip/vip_counts)*100 :100).toFixed(2);
						var up_vip_rate   = (new_vip>0? (cyclevip_buy_count/new_vip)*100 :0).toFixed(2);
						var buyback_vip_rate = ((buy_count_vip/total_vip)*100).toFixed(2);
						
						document.getElementById("loss_vip_rate").innerHTML =  loss_vip_rate+"%";//流失率
						document.getElementById("loss_vip_count").innerHTML = loss_vip;
						document.getElementById("total_vip1").innerHTML = total_vip;
						document.getElementById("hold_vip_rate").innerHTML = hold_vip_rate+"%";//保留率
						document.getElementById("viphold_count").innerHTML = viphold_count;
						document.getElementById("total_vip2").innerHTML = total_vip;
						document.getElementById("new_vip_rate").innerHTML = new_vip_rate+"%";//增长率
						document.getElementById("new_vip_vount").innerHTML = new_vip;
						document.getElementById("total_vip3").innerHTML = total_vip;
						document.getElementById("goup_vip_rate").innerHTML = up_vip_rate+"%";//转化率
						document.getElementById("goup_vip_count").innerHTML = cyclevip_buy_count;
						document.getElementById("total_vip4").innerHTML = new_vip;
						document.getElementById("buyback_vip_rate").innerHTML = buyback_vip_rate+"%";//购买率
						document.getElementById("buyback_vip_count").innerHTML = buy_count_vip;
						document.getElementById("total_vip5").innerHTML = total_vip;
					}else{
						Public.tips({type: 1, content : "查询失败，请联系管理员!!!"});
					}
				}
			});
		},
		initGrid:function(query_type){
			var begindate = $("#begindate").val();
			var enddate = $("#enddate").val();
			var gridWH = Public.setGrid();
			var colModel = [
			    {label:'操作', name: 'operate', index: 'operate', width:60, fixed:true, formatter: handle.operFmatter, title: false, sortable:false,align:'center'},
		    	{label:'卡号',name: 'vm_cardcode',index:'vm_cardcode',width: 110,align:'left', title: false,fixed:true},
		    	{label:'姓名',name: 'vm_name',index:'vm_name',width: 120, align:'left',title: true},
		    	{label:'手机号码',name: 'vm_mobile',index:'vm_mobile',width: 100, title: false,align:'center'},
		    	{label:'类别',name: 'mt_name',index:'mt_name',width: 120, title: true},
		    	{label:'等级',name: 'gd_name',index:'gd_name',width: 120, title: true},
		    	{label:'性别',name: 'vm_sex',index:'vm_sex',width: 50, title: false,align:'center'},
		    	{label:'周期消费次数',name: 'sh_times',index:'sh_times',width: 100, title: false,align:'right'},
		    	{label:'周期消费金额',name: 'sh_total_money',index:'sh_total_money',width: 100, title: false,align:'right'},
		    	{label:'总消费次数',name: 'vm_times',index:'vm_times',width: 80, title: false,align:'right'},
		    	{label:'总消费金额',name: 'vm_total_money',index:'vm_total_money',width: 100, title: false,align:'right'},
		    	{label:'办卡店铺',name: 'sp_name',index:'sp_name',width: 120, title: false,align:'left'}
		    ];
			$('#grid').jqGrid({
				url:queryurl+'?'+THISPAGE.buildParams()+query_type,
				datatype: 'json',
				width: gridWH.w-12,
				height: gridWH.h-8,
				gridview: true,
				colModel: colModel,
				rownumbers: true,//行号
				pager:'#page',//分页
				pgbuttons:true,
				recordtext:'{0} - {1} 共 {2} 条',  
				multiselect:false,//多选
				viewrecords: true,
				rowNum:config.DATAROWNUM,//每页条数
				rowList:config.DATAROWLIST,//分页条数
				autoScroll: true,
				footerrow :false,
				userDataOnFooter : false,
				shrinkToFit:false,//表格是否自动填充
				jsonReader: {
					root: 'data.list',
					total: 'data.pageInfo.totalPage',
	                page: 'data.pageInfo.currentPage',
	                records: 'data.pageInfo.totalRow',
					repeatitems : false,
					id: 'id'  //图标ID
				},
				loadComplete: function(data){
				},
				loadError: function(xhr, status, error){		
				},
				ondblClickRow:function(rowid,iRow,iCol,e){
				},
				onPaging: function(pgButton) {
				}
		    });
		},
		buildParams : function(){
			var params = '';
			params += 'begindate='+$("#begindate").val();
			params += '&enddate='+$("#enddate").val();
			params += '&vm_shop_code='+$("#vm_shop_code").val();
			params += '&vs_loss_day='+$("#vs_loss_day").val();
			params += '&consumeDayDate='+$("#consumeDayDate").val();
			params += '&consumeDay='+$("#consumeDay").val();
			return params;
		},
		reset:function(){
			$('#sp_name').val('');
			$('#vm_shop_code').val('');
			$('#vs_loss_day').val($('#lossDay').val());
			$('#begindate').val($('#begindate_hid').val());
			$('#enddate').val($('#enddate_hid').val());
		},
		reloadDataByType:function(query_type){
			var params = THISPAGE.buildParams();
			var gridParam={datatype:"json", url:queryurl+"?"+params+"&query_type="+query_type};
			$("#grid").jqGrid('setGridParam',gridParam).trigger("reloadGrid");
		},
		reloadData:function(data){
			var params=THISPAGE.buildParams();
			var gridParam={datatype:"json", url:queryurl+"?"+params+"&query_type=loss"};
			$("#grid").jqGrid('setGridParam',gridParam).trigger("reloadGrid");
		},
		initEvent:function(){
			//查询
			$('#btn_search').on('click', function(e){
				if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
					return ;
				};
				THISPAGE.loadChartLosePie();
				THISPAGE.reloadData();
			});
			//重置
			$('#btn_reset').on('click', function(e){
				e.preventDefault();
				THISPAGE.reset();
			});
			$("#btn_shop").click(function(){
				Utils.doQueryShop();
			});
			$(window).resize(function(){
				Public.resizeSpecifyGrid("grid",111,32);
			});
		}
}

THISPAGE.init();
